<template>
  <div class="flex flex-wrap items-center gap-8px">
    <div v-for="(room, index) in productRooms" :key="room.id" class="select-box room-pic">
      <el-tooltip :content="room.teroomName">
        <div class="relative h-full w-full">
          <el-image :src="room.teroomImgurl" class="h-full w-full" />
            <el-icon class="del-icon"  v-show="!disabled"  @click="handleRemoveRoom(index)"><CloseBold /></el-icon>
        </div>
      </el-tooltip>
    </div>
    <el-tooltip content="选择空间" v-if="canAdd">
      <div class="select-box" @click="openRoomTableSelect">
        <el-icon>
          <plus />
        </el-icon>
      </div>
    </el-tooltip>
  </div>
  <!-- 空间选择对话框（表格形式） -->
  <RoomTableSelect ref="roomTableSelectRef" :multiple="limit != 1" @change="handleRoomSelected" />
</template>
<script lang="ts" setup>
import { listRoomDetails } from '@/api/tearoom/roomDetails/index';
import { RoomDetailsForm, RoomDetailsVO } from '@/api/tearoom/roomDetails/types';
import RoomTableSelect from '@/views/tearoom/roomDetails/components/RoomTableSelect.vue';
import { propTypes } from '@/utils/propTypes';
import { isArray } from '@/utils/is';
import { oneOfType } from 'vue-types';

// 空间列表，一般用于与空间建立关系时使用
// 提供功能：展示空间列表、添加空间、移除空间
defineOptions({ name: 'RoomSelect' });

const props = defineProps({
  modelValue: oneOfType<number | Array<number>>([Number, Array]).isRequired,
  // 限制数量：默认不限制
  limit: propTypes.number.def(Number.MAX_VALUE),
  disabled: propTypes.bool.def(false)
});

// 计算是否可以添加
const canAdd = computed(() => {
  // 情况一：禁用时不可以添加
  if (props.disabled) return false;
  // 情况二：未指定限制数量时，可以添加
  if (!props.limit) return true;
  // 情况三：检查已添加数量是否小于限制数量
  return productRooms.value.length < props.limit;
});

// 空间列表
const productRooms = ref<RoomDetailsForm[]>([]);

watch(
  () => props.modelValue,
  async () => {
    const ids = isArray(props.modelValue)
      ? // 情况一：多选
        props.modelValue
      : // 情况二：单选
        props.modelValue
        ? [props.modelValue]
        : [];
    // 不需要返显
    if (ids.length === 0) {
      productRooms.value = [];
      return;
    }
    // 只有商品发生变化之后，才去查询商品
    if (productRooms.value.length === 0 || productRooms.value.some((room) => !ids.includes(room.id!))) {
      productRooms.value = await listRoomDetails(ids);
    }
  },
  { immediate: true }
);

/** 商品表格选择对话框 */
const roomTableSelectRef = ref();
// 打开对话框
const openRoomTableSelect = () => {
  roomTableSelectRef.value.open(productRooms.value);
};

/**
 * 选择商品后触发
 *
 * @param rooms 选中的商品列表
 */
const handleRoomSelected = (rooms: RoomDetailsVO | RoomDetailsVO[]) => {
  productRooms.value = isArray(rooms) ? rooms : [rooms];
  emitRoomChange();
};

/**
 * 删除商品
 *
 * @param index 商品索引
 */
const handleRemoveRoom = (index: number) => {
  productRooms.value.splice(index, 1);
  emitRoomChange();
};
const emit = defineEmits(['update:modelValue', 'change']);
const emitRoomChange = () => {
  if (props.limit === 1) {
    const room = productRooms.value.length > 0 ? productRooms.value[0] : null;
    emit('update:modelValue', room?.id || 0);
    emit('change', room);
  } else {
    emit(
      'update:modelValue',
      productRooms.value.map((room) => room.id)
    );
    emit('change', productRooms.value);
  }
};
</script>

<style lang="scss" scoped>
.select-box {
  display: flex;
  width: 60px;
  height: 60px;
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
}

.room-pic {
  position: relative;
}

.del-icon {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  width: 20px !important;
  height: 20px !important;
}
</style>
